package com.wonders.hisdoctor.station.project.medicine.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.wonders.his.common.exception.CustomException;
import com.wonders.his.common.service.project.base.domain.AppBaseParam;
import com.wonders.his.common.service.project.base.domain.BaseDeptDict;
import com.wonders.his.common.service.project.base.mapper.AppBaseParamMapper;
import com.wonders.his.common.service.project.dispense.domain.DrugStatusRec;
import com.wonders.his.common.service.project.dispense.service.DrugStatusRecService;
import com.wonders.his.common.service.project.drugs.service.IDrugConfigurationService;
import com.wonders.his.common.service.project.drugs.service.IStorageTypeService;
import com.wonders.his.common.service.project.drugs.vo.DrugConfiguration;
import com.wonders.his.common.service.project.drugs.vo.PatientType;
import com.wonders.his.common.service.project.drugs.vo.PharmacyType;
import com.wonders.his.common.service.project.enums.PrescStatusEnum;
import com.wonders.his.common.utils.DateUtils;
import com.wonders.his.common.utils.StringUtils;
import com.wonders.his.framework.utils.oracle.IdUtils;
import com.wonders.hisdoctor.station.constant.Constants;
import com.wonders.hisdoctor.station.constant.ServiceConstant;
import com.wonders.hisdoctor.station.enums.AppBaseParamEnum;
import com.wonders.hisdoctor.station.enums.AppBaseParamTypeEnum;
import com.wonders.hisdoctor.station.enums.OracleSequenceEnum;
import com.wonders.hisdoctor.station.project.base.domain.*;
import com.wonders.hisdoctor.station.project.base.mapper.*;
import com.wonders.hisdoctor.station.project.hisqueue.vo.ClinicMasterQueryVo;
import com.wonders.hisdoctor.station.project.medicine.enums.ChargeIndicatorEnum;
import com.wonders.hisdoctor.station.project.medicine.enums.ItemClassEnum;
import com.wonders.hisdoctor.station.project.medicine.mapper.MedicineMapper;
import com.wonders.hisdoctor.station.project.medicine.service.ICipherPrescSerive;
import com.wonders.hisdoctor.station.project.medicine.service.MedicineService;
import com.wonders.hisdoctor.station.project.medicine.vo.*;
import com.wonders.hisdoctor.station.project.record.vo.*;
import com.wonders.hisdoctor.station.util.CommonUtil;
import com.wonders.hisdoctor.station.util.ConvertUtils;
import com.wonders.hisdoctor.station.util.PrecsIdGenerator;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.math.BigDecimal;
import java.text.NumberFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author 张澎_9970
 * @date 2021/1/20 15:34 星期三
 * desc: 门诊用药_service_实现
 */
@Slf4j
@Service
public class MedicineServiceImpl implements MedicineService {

    private OutpOrdersMapper outpOrdersMapper;
    private OutpOrdersTMapper outpOrdersTmapper;
    private OutpPrescMapper outpPrescMapper;
    private OutpPrescTMapper outpPrescTmapper;
    private MedicineMapper medicineMapper;
    private ClinicMasterMapper clinicMasterMapper;
    private OutpMrMapper outpMrMapper;
    private IdUtils idUtils;
    private PrecsIdGenerator precsIdGenerator;
    private DrugStatusRecService drugStatusRecService;
    private IStorageTypeService storageTypeService;
    private AppBaseParamMapper appBaseParamMapper;
    private DeptDictMapper deptDictMapper;
    private ICipherPrescSerive cipherPrescSerive;
    private IDrugConfigurationService drugConfigurationService;
    private AdministrationDictMapper administrationDictMapper;
    private IdentityDictMapper identityDictMapper;
    private StaffDictMapper staffDictMapper;
    private HospitalDictMapper hospitalDictMapper;
    private OutpPrescClassMapper outpPrescClassMapper;
    private AppStaticDetailMapper appStaticDetailMapper;
    private PatAllergyMapper patAllergyMapper;
    private CommonUtil commonUtil;


    @Override
    @Transactional(rollbackFor = Exception.class)
    public int save(MedicineVO medicineVO) {
        log.info("##### medicineVO:[" + JSON.toJSONString(medicineVO) + "]");
        // 重复开药全局配置
        AppBaseParam param;
        param = commonUtil.getAppBaseParam(medicineVO.getHospitalCode(),AppBaseParamEnum.CHECK_REPEATABLE.getCode(),ServiceConstant.HOSPITAL_LONG);
        if (param != null && Constants.VALIDATE.equals(param.getValueName())) {
            // 优先进行重复开药判断
            checkRepeatable(medicineVO);
        }

        // 过敏测试全局配置
        param = commonUtil.getAppBaseParam(medicineVO.getHospitalCode(),AppBaseParamEnum.CHECK_ALLERGIC.getCode(),ServiceConstant.HOSPITAL_LONG);
        if (param != null && Constants.VALIDATE.equals(param.getValueName())) {
            // 判断过敏实验是否存在历史出现过阳性
            checkAllergy(medicineVO);
        }

        // save 落表
        return addOrUpdate(medicineVO);
    }

    private int addOrUpdate(MedicineVO medicineVO) {
        List<OutpPresc> addList = new ArrayList<>();
        List<OutpPresc> modList = new ArrayList<>();
        List<OutpPrescT> addTmpList = new ArrayList<>();
        List<OutpPrescT> modTmpList = new ArrayList<>();
        int itemNo = 0;
        String serialNo = null;
        Map<Integer, String> presNoMap = new HashMap<>(9);
        for (PrescriptionVO vo : medicineVO.getPrescriptionVOList()) {
            // 校验库存: 新开单, 已开单, 且非自备
            if (!(vo.getStatus() > ChargeIndicatorEnum.NO_CHARGE.getCode() || vo.getProvidedIndicator().equals(ChargeIndicatorEnum.CHARGED.getCode()))) {
                saveCheck(vo);
            }

            // 修改单_集合
            if (StringUtils.isNotEmpty(vo.getPrescId())) {
                OutpPresc outpPresc = new OutpPresc();
                OutpPrescT outpPrescT = new OutpPrescT();
                // 已缴费之后的, 保存时, 不再操作
                String serialNum = vo.getSerialNo();
                int itemNum = vo.getItemNo() == null ? 0 : vo.getItemNo();
                if (StringUtils.isNotEmpty(serialNum) && itemNum > 0) {
                    QueryWrapper<OutpPresc> wrapper = new QueryWrapper<>();
                    wrapper.eq(ServiceConstant.SERIAL_NO, serialNum);
                    wrapper.eq(ServiceConstant.ITEM_NO, itemNum);
                    OutpPresc result = outpPrescMapper.selectOne(wrapper);
                    if (result != null && result.getChargeIndicator() > 0) {
                        continue;
                    }
                }
                BeanUtils.copyProperties(vo, outpPresc);
                BeanUtils.copyProperties(outpPresc, outpPrescT);
                modList.add(outpPresc);
                modTmpList.add(outpPrescT);
                continue;
            }
            Integer prescNo = vo.getPrescNo();

            // 使用computeIfAbsent，判断是否key对应的value为空
            presNoMap.computeIfAbsent(prescNo, k -> {
                String prescId = precsIdGenerator.getPrescId();
                // 新增_状态表
                DrugStatusRec statusRec = new DrugStatusRec();
                statusRec.setPrescId(prescId);
                statusRec.setDispensary(vo.getDispensary());
                statusRec.setStatusDate(new Date());
                statusRec.setPrescStatus(PrescStatusEnum.HAVE_ORDER.getCode());
                statusRec.setOperatorNo(medicineVO.getOutpOrders().getEmpNo());
                drugStatusRecService.insert(statusRec);
                return prescId;
            });

            // 新处方, 生成流水号
            serialNo = serialNo != null ? serialNo
                    : idUtils.getNextVal(OracleSequenceEnum.SEQ_OUTP_ORDERS.getCode()).toString();
            // 新增单_集合
            OutpPresc outpPresc = new OutpPresc();
            OutpPrescT outpPrescT = new OutpPrescT();
            BeanUtils.copyProperties(vo, outpPresc);
            outpPresc.setSerialNo(serialNo);
            outpPresc.setItemNo(++itemNo);
            outpPresc.setChargeIndicator(ChargeIndicatorEnum.NO_CHARGE.getCode());
            outpPresc.setPrescId(presNoMap.get(prescNo));
            BeanUtils.copyProperties(outpPresc, outpPrescT);
            addList.add(outpPresc);
            addTmpList.add(outpPrescT);
        }
        if (!CollectionUtils.isEmpty(addList)) {
            // 新增_主记录
            OutpOrders outpOrders = medicineVO.getOutpOrders();
            outpOrders.setSerialNo(serialNo);
            OutpOrdersT outpOrdersT = new OutpOrdersT();
            BeanUtils.copyProperties(outpOrders, outpOrdersT);
            outpOrdersMapper.add(outpOrders);
            outpOrdersTmapper.add(outpOrdersT);
            // 新增_明细表
            outpPrescMapper.batchInsert(addList);
            outpPrescTmapper.batchInsert(addTmpList);
        }
        if (!CollectionUtils.isEmpty(modList)) {
            // 修改_明细表
            outpPrescMapper.batchUpdate(modList);
            outpPrescTmapper.batchUpdate(modTmpList);
        }
        return addList.size() + modList.size();
    }

    private void saveCheck(PrescriptionVO vo) {
        // 校验天数不能大于3位数
        if (vo.getPrescDuration() != null && vo.getPrescDuration() > ServiceConstant.MAX_DURATION) {
            throw new CustomException("天数不能大于3位数字, 请核对参数!");
        }
        // 修改前的数量
        BigDecimal beforeAmount = BigDecimal.ZERO;
        QueryWrapper<OutpPresc> wrapper = new QueryWrapper<>();
        if (vo.getSerialNo() != null) {
            wrapper.eq(ServiceConstant.SERIAL_NO, vo.getSerialNo());
            wrapper.eq(ServiceConstant.ITEM_NO, vo.getItemNo());
            wrapper.eq(ServiceConstant.DRUG_CODE, vo.getDrugCode());
            wrapper.eq(ServiceConstant.DRUG_SPEC, vo.getDrugSpec());
            wrapper.eq(ServiceConstant.FIRM_ID, vo.getFirmId());
            wrapper.eq(ServiceConstant.DISPENSARY, vo.getDispensary());
            OutpPresc outpPresc = outpPrescMapper.selectOne(wrapper);
            if (outpPresc != null) {
                // 数量未增加, 不校验库存
                if (vo.getAmount().intValue() <= outpPresc.getAmount().intValue()) {
                    return;
                }
                beforeAmount = outpPresc.getAmount();
            }
        }

        // 数量_本次开出
        BigDecimal amount = vo.getAmount();

        // 数量_已开出的
        BigDecimal frozenQuantity;
        try {
            frozenQuantity = medicineMapper.getFrozenQuantity(vo);
        } catch (Exception e) {
            throw new CustomException("药品: [" + vo.getDrugName() + ", " + vo.getDrugSpec() + "], 已下柜, 清重新选择");
        }

        List<BaseDeptDict> storageDeptList = storageTypeService.getDeptList(vo.getHospitalCode(), PatientType.OUT_PATIENT, PharmacyType.DRUG_ROOM);
        List<String> storages = new ArrayList<>();
        if (!CollectionUtils.isEmpty(storageDeptList)) {
            storageDeptList.forEach(e -> storages.add(e.getDeptCode()));
        }
        vo.setStorages(storages);

        // 数量_总库存
        DrugConfiguration drugConfiguration = drugConfigurationService.getDrugConfiguration();
        Integer expireRangeDays = drugConfiguration.getExpireRangeDays();
        vo.setExpireRangeDays(expireRangeDays);
        BigDecimal total = medicineMapper.getTotal(vo);
        if (total == null) {
            throw new CustomException("[" + vo.getDrugName() + "], 无库存!");
        }

        // 可用库存
        BigDecimal subtract = total.subtract(frozenQuantity).add(beforeAmount);

        // 校验
        String units = vo.getUnits();
        if (subtract.compareTo(amount) < 0) {
            throw new CustomException("[" + vo.getDrugName() + "], 可用库存: [" + subtract.intValue() + "]" + units
                    + ", 不足[" + amount.intValue() + "]" + units + ", 请重新输入!");
        }

    }

    /**
     * 查询处方主表 及 明细表
     *
     * @param patientId 病人ID
     * @param visitDate 就诊日期
     * @param visitNo   就诊序号
     * @param empNo     医生编号
     * @return List<OutpOrders>
     */
    @Override
    public List<PrescriptionVO> queryPrescriptions(String patientId, Date visitDate, Integer visitNo, String
            empNo, Integer isHistory) {
        return medicineMapper.queryPrescriptions(patientId, visitDate, visitNo, empNo, isHistory);
    }

    /**
     * @param qryPresVO qryPresVO
     * @return List<PrescriptionVO>
     */
    @Override
    public List<PrescriptionVO> qryPres(QryPresVO qryPresVO) {
        qryPresVO.setDate(DateUtils.dateFormatDate(DateUtils.YYYY_MM_DD, new Date()));
        List<PrescriptionVO> list = medicineMapper.qryPres(qryPresVO);
        // 计算_药品种数
        Map<Integer, Integer> map = new HashMap<>(9);
        int num = 1;
        for (PrescriptionVO vo : list) {
            Integer prescNo = vo.getPrescNo();
            num = !map.containsKey(prescNo) ? 1 : ++num;
            map.put(prescNo, num);
        }
        for (PrescriptionVO vo : list) {
            vo.setNumber(map.get(vo.getPrescNo()));
        }
        return list;
    }

    /**
     * 查询患者_就诊记录
     */
    @Override
    public List<ClinicMasterQueryVo> qryClinic(QryClinicVO qryClinicVO) {
        return medicineMapper.qryClinic(qryClinicVO);
    }

    @Override
    public AppBaseParam medicineRepeatable(String orgId) {
        AppBaseParam appBaseParam = new AppBaseParam();
        appBaseParam.setKeyName(AppBaseParamEnum.MEDICINE_REPEATABLE.getCode());
        appBaseParam.setType(AppBaseParamTypeEnum.HOSPITAL.getType());
        appBaseParam.setTypeValue(orgId);
        AppBaseParam result = appBaseParamMapper.selectOne(appBaseParam);
        if (result == null) {
            appBaseParam.setType(AppBaseParamTypeEnum.GLOBAL.getType());
            appBaseParam.setTypeValue("");
            result = appBaseParamMapper.selectOne(appBaseParam);
        }
        return result;
    }

    /**
     * Description: 打印输液单
     * Param: [request]
     * return: com.wonders.hisdoctor.station.project.medicine.vo.TransfusionVo
     * Author: tong-aj
     * Date: 2021/5/24
     */
    @Override
    public TransfusionVo getTransfusion(TransfusionRequest request) {
        String patientId = request.getPatientId();
        Date visitDate = request.getVisitDate();
        String visitNo = request.getVisitNo();
        String empNo = request.getEmpNo();
        String hospitalCode = request.getHospitalCode();

        TransfusionVo transfusionVo = new TransfusionVo();
        // 处理处方打印标题
        transfusionVo.setTitle(commonUtil.setPrintTitle(hospitalCode));

        HospitalDict hospitalDict = hospitalDictMapper.selectOne(new QueryWrapper<HospitalDict>().eq(ServiceConstant.HOSPITAL_CODE, hospitalCode));
        transfusionVo.setHospitalName(hospitalDict.getHospitalName());

        StaffDict staffDict = staffDictMapper.selectOne(new QueryWrapper<StaffDict>().eq(ServiceConstant.EMP_NO, empNo));
        transfusionVo.setDoctorsName(staffDict.getName());

        transfusionVo.setPatAge(commonUtil.getAge(patientId));
        // 组装病人信息
        QueryWrapper<ClinicMaster> clinicMasterQueryWrapper = new QueryWrapper<>();
        clinicMasterQueryWrapper.eq(ServiceConstant.VISIT_DATE, visitDate).eq(ServiceConstant.VISIT_NO, visitNo).eq(ServiceConstant.PATIENT_ID, patientId);
        ClinicMaster clinicMaster = clinicMasterMapper.selectOne(clinicMasterQueryWrapper);
        if (clinicMaster != null) {
            ConvertUtils.convertClinicMasterToTransfusionVo(transfusionVo, clinicMaster);
            //身份转name
            IdentityDict identity = identityDictMapper.selectOne(new QueryWrapper<IdentityDict>().eq(ServiceConstant.IDENTITY_CODE, transfusionVo.getIdentity()));
            transfusionVo.setIdentity(identity.getIdentityName());
            //科室转name
            DeptDict deptDict = deptDictMapper.selectOne(new QueryWrapper<DeptDict>().eq(ServiceConstant.DEPT_CODE, clinicMaster.getVisitDept()));
            transfusionVo.setDepName(deptDict.getDeptName());
            // 组装病历信息
            QueryWrapper<OutpMr> outpMrQueryWrapper = new QueryWrapper<>();
            outpMrQueryWrapper.eq(ServiceConstant.VISIT_DATE, visitDate).eq(ServiceConstant.VISIT_NO, visitNo).eq(ServiceConstant.PATIENT_ID, patientId).eq(ServiceConstant.DOCTOR, empNo);
            OutpMr outpMr = outpMrMapper.selectOne(outpMrQueryWrapper);
            if (outpMr != null) {
                ConvertUtils.convertOutpMrToTransfusionVo(transfusionVo, outpMr);
            }
        }
        AppBaseParam appBaseParam = commonUtil.getAppBaseParam(hospitalCode, ServiceConstant.TRANSFUSION_LOCATION, AppBaseParamTypeEnum.HOSPITAL.getType());
        if (appBaseParam != null && StringUtils.isNotEmpty(appBaseParam.getValueName()) && !appBaseParam.getValueName().equals(ServiceConstant.SEPERATER)) {
            String[] split = appBaseParam.getValueName().split(ServiceConstant.SEPERATER);
            transfusionVo.setDeptName(split[0]);
            transfusionVo.setLocation(split[1]);
        }
        transfusionVo.setPrintTime(DateUtils.dateFormatTime(new Date(), ServiceConstant.YYYY_MM_DD_HH_MM_SS_CN));
        return transfusionVo;
    }

    /**
     * 用量配置
     *
     * @param hospitalCode 机构代码
     * @return DosageConfigVO
     */
    @Override
    public DosageConfigVO dosageConfig(String hospitalCode) {
        final DosageConfigVO dosageConfigVO = new DosageConfigVO();
        final AppBaseParam appBaseParam = new AppBaseParam();
        appBaseParam.setKeyName(AppBaseParamEnum.DOSAGE.getCode());
        appBaseParam.setType(AppBaseParamTypeEnum.HOSPITAL.getType());
        appBaseParam.setTypeValue(hospitalCode);
        AppBaseParam param = appBaseParamMapper.selectOne(appBaseParam);
        if (param == null) {
            appBaseParam.setType(AppBaseParamTypeEnum.GLOBAL.getType());
            appBaseParam.setTypeValue("");
            param = appBaseParamMapper.selectOne(appBaseParam);
        }
        if (param != null) {
            final String valueName = param.getValueName()
                    .replace("，", ",")
                    .replace(" ", "");
            final String[] array = valueName.split(",");
            Integer prescDuration = Integer.valueOf(array[array.length - 1]);
            String[] configArr = new String[array.length - 1];
            System.arraycopy(array, 0, configArr, 0, array.length - 1);
            dosageConfigVO.setDrugDosages(configArr);
            dosageConfigVO.setPrescDuration(prescDuration);
        }
        return dosageConfigVO;
    }

    /**
     * 根据剂型获取给药方式
     *
     * @param drugCode 药品代码
     * @param drugSpec 药品规格
     * @return Map
     */
    @Override
    public Map<String, String> getAdminByForm(String drugCode, String drugSpec) {
        return medicineMapper.getAdminByForm(drugCode, drugSpec);
    }

    /**
     * Description: 医嘱名称下拉列表
     * Param: [drugListRequest]
     * return: java.util.List<com.wonders.hisdoctor.station.project.record.vo.DrugListVo>
     * Author: tong-aj
     * Date: 2021/3/5
     */
    @Override
    public List<DrugListVo> drugList(DrugListRequest drugListRequest) {

        // 返回数量
        int rowNum = drugListRequest.getRowNum();
        // 默认查询类型
        String defaultType = drugListRequest.getDefaultType();
        // 机构
        String hospitalCode = drugListRequest.getHospitalCode();
        // 特定药品名称信息
        List<DrugListSingleVo> list = drugListRequest.getList();

        // 调用公共接口，获取机构下的门诊药房storageCodes
        List<BaseDeptDict> deptList = storageTypeService.getDeptList(hospitalCode, PatientType.OUT_PATIENT, PharmacyType.DRUG_ROOM);

        // 如果获取的药房为空，则直接返回
        if (CollectionUtils.isEmpty(deptList)) {
            return new ArrayList<>();
        }
        List<String> storages = deptList.stream().map(BaseDeptDict::getDeptCode).collect(Collectors.toList());

        // 调用公共方法获取有效日期提前量
        DrugConfiguration drugConfiguration = drugConfigurationService.getDrugConfiguration();
        Integer expireRangeDays = 0;
        if (drugConfiguration != null) {
            expireRangeDays = drugConfiguration.getExpireRangeDays();
        }
        List<DrugListVo> result;
        // 如果特定药品名称信息不为空，则只查询相应药品
        if (!CollectionUtils.isEmpty(list)) {
            List<String> drugNames = new ArrayList<>(list.size());
            list.forEach(drug -> drugNames.add(drug.getDrugName().toUpperCase()));
            List<String> types = list.stream().map(DrugListSingleVo::getType).distinct().collect(Collectors.toList());
            if (types.size() == 1 && types.get(0).equals(ServiceConstant.ONE_STRING)) {
                types.add(ServiceConstant.ZERO_STRING);
            }
            result = medicineMapper.drugList(drugNames, hospitalCode, types, 0, storages, expireRangeDays);
        } else {
            List<String> defaultTypes = new ArrayList<>();
            // 如果没有传特定药品，则查rowNum数量的处方明细
            if (defaultType.equals(ServiceConstant.ONE_STRING)) {
                defaultTypes.add(ServiceConstant.ONE_STRING);
                defaultTypes.add(ServiceConstant.ZERO_STRING);
            } else {
                defaultTypes.add(ServiceConstant.TWO_STRING);
            }
            result = medicineMapper.drugList(null, hospitalCode, defaultTypes, rowNum, storages, expireRangeDays);
        }
        if (!CollectionUtils.isEmpty(result)) {
            for (DrugListVo vo : result) {
                if (!StringUtils.isEmpty(vo.getDrugCode()) && vo.getDosePerUnit() != null) {
                    vo.setUnits(vo.getDosePerUnit().toString() + vo.getDoseUnits());
                }
            }
            checkQuantity(result);
        }
        if (rowNum != 0 && rowNum < result.size()) {
            return result.subList(0, rowNum - 1);
        }
        return result;
    }

    /**
     * 耗材下拉框
     *
     * @param drugName     耗材名称
     * @param hospitalCode 机构代码
     * @param type         药品类型
     * @return List<SuppliesVo>
     */
    @Override
    public List<SuppliesVo> supplies(String drugName, String hospitalCode, String type) {
        return medicineMapper.supplier(drugName, hospitalCode, type);
    }

    /**
     * 引用处方_左列表
     *
     * @param empNo     人员编号
     * @param patName   患者姓名
     * @param startDate 开始日期
     * @param endDate   结束日期
     * @return List<QuotePrescLeftVo>
     */
    @Override
    public List<QuotePrescLeftVo> quotePrescLeft(String empNo, String patName, Date startDate, Date endDate) {
        return medicineMapper.quotePrescLeft(empNo, patName, startDate, endDate);
    }

    /**
     * 引用处方_右列表
     *
     * @param empNo     人员编号
     * @param patName   患者姓名
     * @param visitDate 开始日期
     * @return List<OutpPresc>
     */
    @Override
    public List<QuotePrescVo> quotePrescription(String empNo, String patName, Date visitDate) {
        return medicineMapper.quotePrescription(empNo, patName, visitDate);
    }

    /**
     * 治疗单打印
     *
     * @param treatPrintVo 门诊药物治疗单打印_入参_VO
     * @return DrugTreatPrintVo
     */
    @Override
    public DrugTreatPrintVo drugTreatPrint(TreatPrintVo treatPrintVo) {
        // 只打印配置的
        AppBaseParam appBaseParam = new AppBaseParam();
        appBaseParam.setKeyName(AppBaseParamEnum.MEDICINE_PRINT.getCode());
        appBaseParam.setType(AppBaseParamTypeEnum.HOSPITAL.getType());
        appBaseParam.setTypeValue(treatPrintVo.getHospitalCode());
        AppBaseParam param = appBaseParamMapper.selectOne(appBaseParam);
        List<CompPkVo> compPkVos = treatPrintVo.getCompPkVos();
        if (param == null) {
            appBaseParam.setType(AppBaseParamTypeEnum.GLOBAL.getType());
            appBaseParam.setTypeValue("");
            param = appBaseParamMapper.selectOne(appBaseParam);
        }
        if (param != null) {
            String valueName = param.getValueName();
            String[] nameArr = valueName.split(",");
            List<String> codeList = administrationDictMapper.selectByName(nameArr);
            List<CompPkVo> compPkVoList = new ArrayList<>();
            for (CompPkVo compPkVo : compPkVos) {
                String administrationCode = compPkVo.getAdministration();
                for (String code : codeList) {
                    if (administrationCode.equals(code)) {
                        compPkVo.setAdministration(code);
                    }
                    compPkVoList.add(compPkVo);
                }
            }
            treatPrintVo.setCompPkVos(compPkVoList);
        }
        if (!CollectionUtils.isEmpty(treatPrintVo.getCompPkVos())) {
            treatPrintVo.setSerialNo(treatPrintVo.getCompPkVos().get(0).getSerialNo());
        } else {
            treatPrintVo.setSerialNo(compPkVos.get(0).getSerialNo());
        }
        OutpOrderVo outpOrderVo = medicineMapper.queryOutpOrder(treatPrintVo);
        outpOrderVo.setAge(commonUtil.getAge(treatPrintVo.getPatientId()));
        outpOrderVo.setTitle(commonUtil.setPrintTitle(treatPrintVo.getHospitalCode()));
        List<OutpPrescVo> outpPrescVos = medicineMapper.queryPrescs(treatPrintVo);
        List<OutpPrescVo> outpPrescVoList = new ArrayList<>();
        // 处理用量
        for (OutpPrescVo outpPrescVo : outpPrescVos) {
            final String dosageUnits = outpPrescVo.getDosageUnits();
            if (StringUtils.isNotEmpty(dosageUnits)) {
                AppBaseParam baseParam = commonUtil.getAppBaseParam(treatPrintVo.getHospitalCode(), ServiceConstant.DOSAGE, ServiceConstant.GLOBAL_CONFIG_ORGAN);
                if (baseParam != null && baseParam.getValueName().contains(outpPrescVo.getDosageUnits())) {
                    outpPrescVo.setDrugDosage(outpPrescVo.getDosageUnits());
                    outpPrescVo.setDosageUnits(null);
                } else {
                    String[] s = dosageUnits.split(" ");
                    double dosageUnit = Double.parseDouble(s[0]);
                    double dosageResult = dosageUnit * outpPrescVo.getDosage().doubleValue();
                    double result = BigDecimal.valueOf(dosageResult).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
                    if (s.length == 2) {
                        outpPrescVo.setDrugDosage(result + s[1]);
                    } else if (s.length == 1) {
                        outpPrescVo.setDrugDosage(String.valueOf(result));
                    }
                }
            }
            outpPrescVoList.add(outpPrescVo);
        }
        DrugTreatPrintVo drugTreatPrintVo = new DrugTreatPrintVo();
        drugTreatPrintVo.setOutpOrderVo(outpOrderVo);
        drugTreatPrintVo.setOutpPrescVos(outpPrescVoList);
        return drugTreatPrintVo;
    }

    /**
     * 批量删
     *
     * @param outpPrescs 处方明细表
     * @return int
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int deleteBatch(List<OutpPresc> outpPrescs) {
        // 检验处方状态是否大于 0 | 0-已开单
        List<QueryPrescStatusVO> prescStatusVOList = medicineMapper.queryPrescStatus(outpPrescs);
        StringBuilder msg = new StringBuilder();
        if (!CollectionUtils.isEmpty(prescStatusVOList)) {
            for (QueryPrescStatusVO vo : prescStatusVOList) {
                msg.append("[").append(vo.getDrugName()).append(",").append(vo.getPrescStatus()).append("]、");
            }
            throw new CustomException(msg.substring(0, msg.toString().lastIndexOf("、")) + ", 无法删除，请重新选择");
        }

        // 删除_处方表
        int delNumPrsc = outpPrescMapper.deleteBatch((outpPrescs));
        outpPrescTmapper.deleteBatch(outpPrescs);

        // 删除_主记录
        HashSet<String> serialNos = new HashSet<>();
        for (OutpPresc outpPresc : outpPrescs) {
            serialNos.add(outpPresc.getSerialNo());
        }
        for (String serialNo : serialNos) {
            QueryWrapper<OutpPresc> queryPrescWrapper = new QueryWrapper<>();
            queryPrescWrapper.eq(ServiceConstant.SERIAL_NO, serialNo);
            if (outpPrescMapper.selectCount(queryPrescWrapper) == 0) {
                OutpOrders outpOrders = new OutpOrders();
                OutpOrdersT outpOrdersT = new OutpOrdersT();
                outpOrdersMapper.deleteById(outpOrders.setSerialNo(serialNo));
                outpOrdersTmapper.deleteById(outpOrdersT.setSerialNo(serialNo));
            }
        }
        return delNumPrsc;
    }

    @Override
    public PrintVo print(MedicinePrintRequest medicinePrintRequest) {
        String patientId = medicinePrintRequest.getPatientId();
        List<String> prescIds = medicinePrintRequest.getPrescIds();
        Date visitDate = medicinePrintRequest.getVisitDate();
        String visitNo = medicinePrintRequest.getVisitNo();
        String empNo = medicinePrintRequest.getEmpNo();
        String hospitalCode = medicinePrintRequest.getHospitalCode();

        PrintVo printVo = new PrintVo();
        // 处理处方打印标题
        printVo.setTitle(commonUtil.setPrintTitle(hospitalCode));

        HospitalDict hospitalDict = hospitalDictMapper.selectOne(new QueryWrapper<HospitalDict>().eq(ServiceConstant.HOSPITAL_CODE, hospitalCode));
        printVo.setHospitalName(hospitalDict.getHospitalName());

        StaffDict staffDict = staffDictMapper.selectOne(new QueryWrapper<StaffDict>().eq(ServiceConstant.EMP_NO, empNo));
        printVo.setDoctorsName(staffDict.getName());

        List<PatAllergy> patAllergyList = patAllergyMapper.selectList(
                new QueryWrapper<PatAllergy>().
                        eq(ServiceConstant.PATIENT_ID, patientId).
                        eq(ServiceConstant.STATUS, ServiceConstant.ONE_STRING).
                        eq(ServiceConstant.ALLERGY_RESULT, ServiceConstant.TWO_STRING));
        List<String> allergyNames = patAllergyList.stream().map(PatAllergy::getAllergyTypeName).collect(Collectors.toList());
        if (!CollectionUtils.isEmpty(allergyNames)) {
            printVo.setAllergyTest(allergyNames.toString().substring(1, allergyNames.toString().length() - 1));
        }
        printVo.setPatAge(commonUtil.getAge(patientId));
        // 组装病人信息
        QueryWrapper<ClinicMaster> clinicMasterQueryWrapper = new QueryWrapper<>();
        clinicMasterQueryWrapper.eq(ServiceConstant.VISIT_DATE, visitDate).eq(ServiceConstant.VISIT_NO, visitNo).eq(ServiceConstant.PATIENT_ID, patientId);
        ClinicMaster clinicMaster = clinicMasterMapper.selectOne(clinicMasterQueryWrapper);
        if (clinicMaster != null) {
            ConvertUtils.convertClinicMasterToPrintVO(printVo, clinicMaster);
            //身份转name
            IdentityDict identity = identityDictMapper.selectOne(new QueryWrapper<IdentityDict>().eq(ServiceConstant.IDENTITY_CODE, printVo.getIdentity()));
            printVo.setIdentity(identity.getIdentityName());
            //科室转name
            DeptDict deptDict = deptDictMapper.selectOne(new QueryWrapper<DeptDict>().eq(ServiceConstant.DEPT_CODE, clinicMaster.getVisitDept()));
            printVo.setDepName(deptDict.getDeptName());
            // 组装病历信息
            QueryWrapper<OutpMr> outpMrQueryWrapper = new QueryWrapper<>();
            outpMrQueryWrapper.eq(ServiceConstant.VISIT_DATE, visitDate).eq(ServiceConstant.VISIT_NO, visitNo).eq(ServiceConstant.PATIENT_ID, patientId).eq(ServiceConstant.DOCTOR, empNo);
            OutpMr outpMr = outpMrMapper.selectOne(outpMrQueryWrapper);
            if (outpMr != null) {
                ConvertUtils.convertOutpMrToPrintVO(printVo, outpMr);
            }
            // 获取所有选择的处方明细
            List<OutpPresc> prescList = outpPrescMapper.selectList(new QueryWrapper<OutpPresc>().in(ServiceConstant.PRESC_ID, prescIds));

            if (!CollectionUtils.isEmpty(prescList)) {
                List<PrintOutpOrdersVO> printOutpOrdersVos = new ArrayList<>();
                prescIds.forEach(prescId -> {
                    List<OutpPresc> prescs = prescList.stream().filter(outpPresc -> outpPresc.getPrescId().equals(prescId)).collect(Collectors.toList());

                    PrintOutpOrdersVO printOutpOrdersVO = new PrintOutpOrdersVO();
                    prescs.stream().map(OutpPresc::getDispensary).distinct().findFirst().ifPresent(code -> {
                        DeptDict dept = deptDictMapper.selectOne(new QueryWrapper<DeptDict>().eq(ServiceConstant.DEPT_CODE, code));
                        printOutpOrdersVO.setPharmacyName(dept.getDeptName());
                    });
                    printOutpOrdersVO.setPrescId(prescId);
                    printOutpOrdersVO.setRepetition(prescs.get(0).getRepetition());
                    printOutpOrdersVO.setHerbUsage(prescs.get(0).getHerbUsage());
                    List<PrintOutpPrescVO> printOutpPrescVos = new ArrayList<>();
                    for (OutpPresc entity : prescs) {
                        PrintOutpPrescVO printOutpPrescVO = new PrintOutpPrescVO();
                        printOutpPrescVO.setDrugName(entity.getDrugName());
                        if (entity.getItemClass().equals(ItemClassEnum.CHINESE_MEDICINE.getCode())) {
                            printOutpPrescVO.setQuantity(NumberFormat.getInstance().format(entity.getAmount().doubleValue()));
                        } else {
                            printOutpPrescVO.setQuantity(entity.getAmount().toString());
                        }
                        printOutpPrescVO.setUnits(entity.getUnits());
                        printOutpPrescVO.setGroupFlag(entity.getGroupFlag());
                        printOutpPrescVO.setSpecification(entity.getDrugSpec());
                        printOutpPrescVO.setFrequency(entity.getFrequency());
                        if (StringUtils.isNotEmpty(entity.getAdministration())) {
                            AdministrationDict administrationDict = administrationDictMapper.selectOne(new QueryWrapper<AdministrationDict>().eq(ServiceConstant.ADMINISTRATION_CODE, entity.getAdministration()));
                            if (administrationDict == null) {
                                AppStaticDetail appStaticDetail = appStaticDetailMapper.selectOne(
                                        new QueryWrapper<AppStaticDetail>().eq(ServiceConstant.TYPE_CODE, ServiceConstant.ADMINISTRATION).eq(ServiceConstant.DETAIL_CODE, entity.getAdministration()));
                                printOutpPrescVO.setAdministration(appStaticDetail.getDetailName());
                            } else {
                                printOutpPrescVO.setAdministration(administrationDict.getAdministrationName());
                            }
                        }
                        if (StringUtils.isNotEmpty(entity.getDosageUnits())) {
                            AppBaseParam appBaseParam = commonUtil.getAppBaseParam(hospitalCode, ServiceConstant.DOSAGE, ServiceConstant.GLOBAL_CONFIG_ORGAN);
                            if (appBaseParam != null && appBaseParam.getValueName().contains(entity.getDosageUnits())) {
                                printOutpPrescVO.setInstructions(entity.getDosageUnits());
                            } else {
                                String[] s = entity.getDosageUnits().split(" ");
                                double dosageUnit = Double.parseDouble(s[0]);
                                double dosageResult = dosageUnit * entity.getDosage().doubleValue();
                                double result = BigDecimal.valueOf(dosageResult).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
                                if (s.length == 2) {
                                    printOutpPrescVO.setInstructions(result + s[1]);
                                } else if (s.length == 1) {
                                    printOutpPrescVO.setInstructions(String.valueOf(result));
                                }
                            }

                        }
                        printOutpPrescVos.add(printOutpPrescVO);
                        // 参考药价
                        printOutpOrdersVO.setPrice(entity.getCosts().add(printOutpOrdersVO.getPrice() == null ? BigDecimal.ZERO : printOutpOrdersVO.getPrice()));
                        // 处方类型
                        OutpPrescClass outpPrescClass = outpPrescClassMapper.selectById(entity.getPrescClass());
                        printOutpOrdersVO.setPrescClass(outpPrescClass.getPrescAlias());

                    }
                    printOutpOrdersVO.setPrintOutpPrescVOS(printOutpPrescVos);
                    // 处理打印时间
                    List<String> serialNos = prescs.stream().map(OutpPresc::getSerialNo).distinct().collect(Collectors.toList());
                    if (serialNos.size() == 1) {
                        String serialNo = serialNos.get(0);
                        OutpOrders outpOrders = outpOrdersMapper.selectOne(new QueryWrapper<OutpOrders>().eq(ServiceConstant.SERIAL_NO, serialNo));
                        printOutpOrdersVO.setPrintTime(DateUtils.formatDate(outpOrders.getOrderDate(), ServiceConstant.YYYY_MM_DD_HH_MM_SS_CN));
                    }
                    printOutpOrdersVos.add(printOutpOrdersVO);
                });
                printVo.setDetailData(printOutpOrdersVos);
            }
        }
        return printVo;
    }


    /**
     * Description: 检验库存
     * Param: [list]
     * return: void
     * Author: tong-aj
     * Date: 2021/4/1
     */
    private void checkQuantity(List<DrugListVo> list) {
        List<Map<String, Object>> sumAmount = outpPrescMapper.getPrescsSumAmount(list);
        list.forEach(vo -> sumAmount.forEach(map -> {
            // 根据四个特定值确定一条数据
            if (map.containsValue(vo.getDrugCode()) &&
                    map.containsValue(vo.getPackageSpec()) &&
                    map.containsValue(vo.getFirmId()) &&
                    map.containsValue(vo.getStorage())) {
                // DrugStock表中的 quantity
                String quantityFromStock = vo.getQuantity();
                int quantityFromStockIntValue = Integer.parseInt(quantityFromStock);
                // 关联状态表，查询明细表中该药品的总合
                int sum = ((BigDecimal) map.get(ServiceConstant.AMOUNT)).intValue();
                // 如果库存大于等于总合，则减
                if (quantityFromStockIntValue >= sum) {
                    int result = Integer.parseInt(quantityFromStock) - sum;
                    vo.setQuantity(String.valueOf(result));
                } else {
                    vo.setQuantity("0");
                }
            }
        }));
    }

    /**
     * 根据上次就诊日期中，每个处方明细的药品是否服用完，来判断当前处方明细是否能开
     * 1：根据条件查询上次就诊记录中，哪些药是重复的
     * 2：重复的处方明细中，根据开药数量*规格/频率 得出需要多久能吃完，查看日期是否被涵盖
     * 3：如果涵盖则提示无法开药
     * return: void
     * Author: tong-aj
     * Date: 2021/2/19
     */
    @Transactional(rollbackFor = Exception.class)
    public void checkRepeatable(MedicineVO medicineVO) {
        // 获取数据
        // 处方主纪录
        OutpOrders outpOrders = medicineVO.getOutpOrders();
        List<PrescriptionVO> prescriptionVOList = medicineVO.getPrescriptionVOList();
        String patientId = outpOrders.getPatientId();
        // 中草药不校验是否重复
        if (prescriptionVOList.get(0).getItemClass().equals(ItemClassEnum.CHINESE_MEDICINE.getCode())) {
            return;
        }
        // 过滤出需要新增的集合
        List<PrescriptionVO> insertVos = prescriptionVOList.stream().filter(vo -> StringUtils.isEmpty(vo.getSerialNo())).collect(Collectors.toList());
        if (!CollectionUtils.isEmpty(insertVos)) {
            // 验证新增的重复开药
            checkInsertRepeatable(insertVos, patientId);
        }

        // 过滤出需要更新的集合
        List<PrescriptionVO> updateVos = prescriptionVOList.stream().filter(vo -> StringUtils.isNotEmpty(vo.getSerialNo())).collect(Collectors.toList());
        if (!CollectionUtils.isEmpty(updateVos)) {
            // 验证更新的重复开药
            checkUpdateRepeatable(updateVos, patientId);
        }
    }

    /**
     * Description: 检测更新时，是否重复开药
     * Param: [prescriptionVos, patientId]
     * return: void
     * Author: tong-aj
     * Date: 2021/3/15
     */
    private void checkUpdateRepeatable(List<PrescriptionVO> prescriptionVOList, String patientId) {
        // 获取更新明细的serialNos
        List<String> serialNos = prescriptionVOList.stream().map(PrescriptionVO::getSerialNo).distinct().collect(Collectors.toList());

        // 根据serialNos查询所有的明细记录
        List<OutpPresc> listFromDb = outpPrescMapper.selectList(new QueryWrapper<OutpPresc>().in(ServiceConstant.SERIAL_NO, serialNos));

        // 移除更新集合中与数据库中相同处方的内容
        listFromDb.forEach(e -> prescriptionVOList.removeIf(vo -> vo.getDrugCode().equals(e.getDrugCode()) && vo.getDrugSpec().equals(e.getDrugSpec())));

        // 如果集合中还有对象，说明时更新时更改了处方明细，变相理解为新增，使用新增验证
        if (!CollectionUtils.isEmpty(prescriptionVOList)) {
            checkInsertRepeatable(prescriptionVOList, patientId);
        }
    }

    /**
     * Description: 检验新增时的重复开药
     * Param: [prescriptionVos]
     * return: void
     * Author: tong-aj
     * Date: 2021/3/15
     */
    private void checkInsertRepeatable(List<PrescriptionVO> prescriptionVOList, String patientId) {
        List<Map<String, String>> list = new ArrayList<>(prescriptionVOList.size());
        // 将请求的处方明细的drugCode和drugSpec以键值对的方式存入list中
        prescriptionVOList.forEach(vo -> {
            Map<String, String> map = new HashMap<>(2);
            map.put("drugCode", vo.getDrugCode());
            map.put("drugSpec", vo.getDrugSpec());
            list.add(map);
        });

        // 根据list和patientId查询该病人这些药最近的服用记录
        List<OutpPresc> lastList = medicineMapper.findLastDrugUseInfo(list, patientId);
        // 没有最近一次记录，直接返回
        if (CollectionUtils.isEmpty(lastList)) {
            return;
        }
        // 获取去重后，处方明细的drugCode集合
        List<String> distinctDrugs = lastList.stream().map(OutpPresc::getDrugCode).distinct().collect(Collectors.toList());

        distinctDrugs.forEach(drug -> {
            // 找到该药品表里 日期最大的明细记录
            OutpPresc outpPresc = lastList.stream().filter(e -> e.getDrugCode().equals(drug)).max(Comparator.comparing(OutpPresc::getVisitDate)).orElse(null);
            if (outpPresc != null) {
                Date lastVisitDate = outpPresc.getVisitDate();
                String drugName = outpPresc.getDrugName();
                Integer days = outpPresc.getPrescDuration();
                if (days != null && org.apache.commons.lang3.time.DateUtils.addDays(lastVisitDate, days).getTime() > System.currentTimeMillis()) {
                    throw new CustomException("当前药品" + drugName + "可服用到" + DateUtils.dateFormatTime(org.apache.commons.lang3.time.DateUtils.addDays(lastVisitDate, days), DateUtils.YYYY_MM_DD) + " ,不能重复开药");
                }
            }
        });
    }


    /**
     * Description: 判断当前录入的明细中，是否存在历史含过敏阳性
     * Param: [prescriptionVos]
     * return: void
     * Author: tong-aj
     * Date: 2021/2/20
     */
    private void checkAllergy(MedicineVO medicineVO) {
        // 获取前端传至后端的明细数据
        List<PrescriptionVO> prescriptionVOList = medicineVO.getPrescriptionVOList();
        if (CollectionUtils.isEmpty(prescriptionVOList)) {
            return;
        }
        // 处方主纪录
        OutpOrders outpOrders = medicineVO.getOutpOrders();
        // 病人编号
        String patientId = outpOrders.getPatientId();
        String serialNo = outpOrders.getSerialNo();
        // 根据病人编号和就诊日期，查出之前所有的处方记录
        QueryWrapper<OutpOrders> wrapper = new QueryWrapper<>();
        wrapper.eq(ServiceConstant.PATIENT_ID, patientId);
        if (!StringUtils.isEmpty(serialNo)) {
            wrapper.ne(ServiceConstant.SERIAL_NO, serialNo);
        }
        // 获取该病人所有的处方主纪录，如果serialNo为空，则不查询当前的
        List<OutpOrders> ordersList = outpOrdersMapper.selectList(wrapper);
        // 存在既往记录，进行过敏测试阳性判断
        if (!CollectionUtils.isEmpty(ordersList)) {
            // 将所有该病人历史明细SerialNo处方加入集合
            List<String> serialNos = ordersList.stream().map(OutpOrders::getSerialNo).collect(Collectors.toList());
            // 查询明细的给药方式是否为皮试
            QueryWrapper<AdministrationDict> administrationDictQueryWrapper = new QueryWrapper<>();
            administrationDictQueryWrapper.like(ServiceConstant.ADMINISTRATION_NAME, ServiceConstant.PISHI);
            List<AdministrationDict> administrationDictList = administrationDictMapper.selectList(administrationDictQueryWrapper);
            // 所有含皮试的给药方式code集合
            List<String> piShiCodes = administrationDictList.stream().map(AdministrationDict::getAdministrationCode).collect(Collectors.toList());
            prescriptionVOList.forEach(vo -> {
                if (!CollectionUtils.isEmpty(administrationDictList)) {
                    // 首先获取明细信息中的必填字段
                    String administration = vo.getAdministration();
                    String drugCode = vo.getDrugCode();
                    String drugSpec = vo.getDrugSpec();
                    // 如果不是皮试，则进行过敏验证
                    if (!piShiCodes.contains(administration) && !CollectionUtils.isEmpty(serialNos)) {
                        // 查询该病人服用该药品的历史
                        QueryWrapper<OutpPresc> queryWrapper = new QueryWrapper<>();
                        queryWrapper.eq(ServiceConstant.DRUG_CODE, drugCode);
                        queryWrapper.eq(ServiceConstant.DRUG_SPEC, drugSpec);
                        queryWrapper.in(ServiceConstant.SERIAL_NO, serialNos);
                        queryWrapper.orderByDesc(ServiceConstant.SERIAL_NO);
                        List<OutpPresc> resultList = outpPrescMapper.selectList(queryWrapper);

                        // 只判断最近一次的
                        if (!CollectionUtils.isEmpty(resultList)) {
                            OutpPresc last = resultList.get(0);
                            if (last.getAllergyTest() != null && last.getAllergyTest().equals(Constants.POSITIVE)) {
                                throw new CustomException("该药品：" + vo.getDrugName() + drugSpec + " 过敏试验阳性，不能开药");
                            }
                        }
                    }
                }
            });
        }
    }

    /**
     * 取消成组
     *
     * @param compPkVos 入参
     * @return Integer
     */
    @Override
    public Integer ungroup(List<CompPkVo> compPkVos) {
        if (CollectionUtils.isEmpty(compPkVos)) {
            return 0;
        }
        List<OutpPresc> updateList = new ArrayList<>();
        for (CompPkVo vo : compPkVos) {
            OutpPresc outpPresc = new OutpPresc();
            if (StringUtils.isNotEmpty(vo.getSerialNo()) && vo.getItemNo() != null) {
                outpPresc.setSerialNo(vo.getSerialNo());
                outpPresc.setItemNo(vo.getItemNo());
                outpPresc.setGroupFlag("");
                updateList.add(outpPresc);
            }
        }
        if (CollectionUtils.isEmpty(updateList)) {
            return 0;
        }
        outpPrescMapper.ungroup(updateList);
        return updateList.size();
    }

    /**
     * 确认转方_校验
     *
     * @param quotePrescVos 入参
     * @param patientId     病人标识
     * @return String
     */
    @Override
    public CipherQuoteVO checkPresc(List<QuotePrescVo> quotePrescVos, String patientId) {
        List<CipherPrescDetailVO> list = new ArrayList<>();
        if (CollectionUtils.isEmpty(quotePrescVos)) {
            return null;
        }
        for (QuotePrescVo quotePrescVo : quotePrescVos) {
            CipherPrescDetailVO detail = new CipherPrescDetailVO();
            BeanUtils.copyProperties(quotePrescVo, detail);
            list.add(detail);
        }
        return cipherPrescSerive.cipherCheck(list, patientId);
    }

    // Setter
    @Autowired
    public void setOutpOrdersMapper(OutpOrdersMapper outpOrdersMapper) {
        this.outpOrdersMapper = outpOrdersMapper;
    }

    @Autowired
    public void setOutpOrdersTmapper(OutpOrdersTMapper outpOrdersTmapper) {
        this.outpOrdersTmapper = outpOrdersTmapper;
    }

    @Autowired
    public void setOutpPrescMapper(OutpPrescMapper outpPrescMapper) {
        this.outpPrescMapper = outpPrescMapper;
    }

    @Autowired
    public void setOutpPrescTmapper(OutpPrescTMapper outpPrescTmapper) {
        this.outpPrescTmapper = outpPrescTmapper;
    }

    @Autowired
    public void setMedicineMapper(MedicineMapper medicineMapper) {
        this.medicineMapper = medicineMapper;
    }

    @Autowired
    public void setClinicMasterMapper(ClinicMasterMapper clinicMasterMapper) {
        this.clinicMasterMapper = clinicMasterMapper;
    }

    @Autowired
    public void setOutpMrMapper(OutpMrMapper outpMrMapper) {
        this.outpMrMapper = outpMrMapper;
    }

    @Autowired
    public void setIdUtils(IdUtils idUtils) {
        this.idUtils = idUtils;
    }

    @Autowired
    public void setPrecsIdGenerator(PrecsIdGenerator precsIdGenerator) {
        this.precsIdGenerator = precsIdGenerator;
    }

    @Autowired
    public void setDrugStatusRecService(DrugStatusRecService drugStatusRecService) {
        this.drugStatusRecService = drugStatusRecService;
    }

    @Autowired
    public void setStorageTypeService(IStorageTypeService storageTypeService) {
        this.storageTypeService = storageTypeService;
    }

    @Autowired
    public void setAppBaseParamMapper(AppBaseParamMapper appBaseParamMapper) {
        this.appBaseParamMapper = appBaseParamMapper;
    }

    @Autowired
    public void setDeptDictMapper(DeptDictMapper deptDictMapper) {
        this.deptDictMapper = deptDictMapper;
    }

    @Autowired
    public void setCipherPrescSerive(ICipherPrescSerive cipherPrescSerive) {
        this.cipherPrescSerive = cipherPrescSerive;
    }

    @Autowired
    public void setDrugConfigurationService(IDrugConfigurationService drugConfigurationService) {
        this.drugConfigurationService = drugConfigurationService;
    }

    @Autowired
    public void setAdministrationDictMapper(AdministrationDictMapper administrationDictMapper) {
        this.administrationDictMapper = administrationDictMapper;
    }

    @Autowired
    public void setIdentityDictMapper(IdentityDictMapper identityDictMapper) {
        this.identityDictMapper = identityDictMapper;
    }

    @Autowired
    public void setStaffDictMapper(StaffDictMapper staffDictMapper) {
        this.staffDictMapper = staffDictMapper;
    }

    @Autowired
    public void setHospitalDictMapper(HospitalDictMapper hospitalDictMapper) {
        this.hospitalDictMapper = hospitalDictMapper;
    }

    @Autowired
    public void setOutpPrescClassMapper(OutpPrescClassMapper outpPrescClassMapper) {
        this.outpPrescClassMapper = outpPrescClassMapper;
    }

    @Autowired
    public void setAppStaticDetailMapper(AppStaticDetailMapper appStaticDetailMapper) {
        this.appStaticDetailMapper = appStaticDetailMapper;
    }

    @Autowired
    public void setPatAllergyMapper(PatAllergyMapper patAllergyMapper) {
        this.patAllergyMapper = patAllergyMapper;
    }

    @Autowired
    public void setCommonUtil(CommonUtil commonUtil) {
        this.commonUtil = commonUtil;
    }
}
